package com.changgou.seckill.service.impl;

import com.alibaba.fastjson.JSON;
import com.changgou.seckill.config.ConfirmMessageSender;
import com.changgou.seckill.config.RabbitMQConfig;
import com.changgou.seckill.dao.SeckillOrderMapper;
import com.changgou.seckill.pojo.SeckillGoods;
import com.changgou.seckill.pojo.SeckillOrder;
import com.changgou.seckill.service.SecKillOrderService;
import com.changgou.utils.IdWorker;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.concurrent.TimeUnit;

@Service
public class SecKillOrderServiceImpl implements SecKillOrderService {

    public static final String SECKILL_GOODS_KEY = "seckill_goods_";
    public static final String SECKILL_GOODS_STOCK_COUNT_KEY = "seckill_goods_stock_count_";

    @Autowired
    private RedisTemplate redisTemplate;


    @Autowired
    private IdWorker idWorker;

    @Autowired
    private ConfirmMessageSender confirmMessageSender;

    @Autowired
    private SeckillOrderMapper seckillOrderMapper;

    @Override
    public boolean add(String time, Long id,String username) {

        //防止恶意刷单 保证一次
        String result = this.preventRepeatCommit(username, id);
        if("fail".equals(result)){
            return false;
        }

        SeckillOrder order = seckillOrderMapper.getSecKillOrderByUserNameAndGoodsId(username, id);
        if(order != null){
            return false;
        }

        //获取商品信息和库存信息，并判断
        SeckillGoods seckillGoods = (SeckillGoods) redisTemplate.boundHashOps(SECKILL_GOODS_KEY + time).get(id);
        String redisStock = (String) redisTemplate.boundValueOps(SECKILL_GOODS_STOCK_COUNT_KEY + id).get();

        //校验
        if(StringUtils.isEmpty(redisStock)){
            return false;
        }
        int stock = Integer.parseInt(redisStock);
        if(seckillGoods==null || stock<=0){//没有库存直接返回
            return false;
        }

        //通过redis的原子性实现预扣减库存操作
        //decrement：-    increment:+    返回值stockCount是扣减完成后的值
        Long stockCount = redisTemplate.opsForValue().decrement(SECKILL_GOODS_STOCK_COUNT_KEY + seckillGoods.getId(),1);
        if(stockCount<=0){
            //库存没了，删除该秒杀商品
            redisTemplate.boundHashOps(SECKILL_GOODS_KEY + time).delete(id);
            redisTemplate.delete(SECKILL_GOODS_STOCK_COUNT_KEY + id);
        }

        if(stockCount<0){
            return false;
        }

        SeckillOrder seckillOrder = new SeckillOrder();
        seckillOrder.setId(idWorker.nextId());
        seckillOrder.setSeckillId(id);
        seckillOrder.setMoney(seckillGoods.getCostPrice());
        seckillOrder.setUserId(username);
        seckillOrder.setSellerId(seckillGoods.getSellerId());
        seckillOrder.setCreateTime(new Date());
        seckillOrder.setStatus("0");

        //发送消息
        confirmMessageSender.sendMessage("", RabbitMQConfig.SECKILL_ORDER_QUEQUE, JSON.toJSONString(seckillOrder));

        return true;
    }


    //防止用户恶意下单
    private String preventRepeatCommit(String username,Long id){
        String redis_key = "seckill_user_"+username+"_id_"+id;
        long count = redisTemplate.opsForValue().increment(redis_key, 1);
        if(count == 1){
            redisTemplate.expire(redis_key,5, TimeUnit.SECONDS);
            return "success";
        }
        if(count>1){
            return "fail";
        }
        return "fail";
    }



}
